package activity.addCamera;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;

import java.util.List;

import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import main.MainActivity;
import utils.EmojiFilter;
import utils.FullCharUnionFilter;
import utils.HiToast;
import utils.HiTools;
import utils.NotCopyAndPaste;

/**
 * 给设备配置 WiFi并添加 (AP模式)
 * Created by lt on 2017\12\27 0027.
 */

public class AddAndConfigWiFiActivity extends HiActivity implements View.OnClickListener, ICameraIOSessionCallback {
    @BindView(R.id.titleview) TitleView titleview;
    @BindView(R.id.et_add_camera_uid) EditText et_add_camera_uid;
    //@BindView(R.id.et_add_camera_nickname) EditText et_add_camera_nickname;
    @BindView(R.id.but_complete) Button but_complete;
    @BindView(R.id.et_add_camera_username) EditText et_add_camera_username;
    @BindView(R.id.et_add_camera_password) EditText et_add_camera_password;

    private String mUid;
    private MyCamera camera;
    private String mSsid;
    private WifiManager wifiManager;
    private String str_uid;
    private String str_username;
    private String str_password;
    private String str_nick;
    private int mType = 0;  //mType==1   确认UID界面  跳转过来的
    //mType==2   确认AP设备的界面  跳转过来的   或者连接设备热点 界面跳过来 不同的是WiFi名字要显示空白

    private String mCurrentPhoneWiFi;
    private boolean isAP = false; //是否是AP跳转过来的  点击添加之后的流程不一样。
    private boolean isSupportFullChar=false;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_config_wifi_to_device;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initViewAndData();
        setListeners();

    }

    private void setListeners() {
        but_complete.setOnClickListener(this);
    }

    private void getIntentData() {
        mUid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        mSsid = getIntent().getStringExtra("ssid");
        mType = getIntent().getIntExtra("type", 0);
        mCurrentPhoneWiFi = getIntent().getStringExtra("mCurrentPhoneWiFi");
        isAP = getIntent().getBooleanExtra("isAP", false);
    }

    private void initViewAndData() {
        titleview.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        titleview.setTitle(getString(R.string.title_equipment_information));
        titleview.setRightTxtBack(R.mipmap.x_bule);
        titleview.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        AddAndConfigWiFiActivity.this.finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_IV_RIGHT:
                        Intent intent = new Intent(AddAndConfigWiFiActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent, true);
                        break;
                }
            }
        });
        et_add_camera_uid.setText(mUid);
        if (!TextUtils.isEmpty(mUid)) {
            et_add_camera_uid.setEnabled(false);
        }
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        et_add_camera_password.setCustomSelectionActionModeCallback(new NotCopyAndPaste());
        et_add_camera_password.setFilters(new InputFilter[]{new InputFilter.LengthFilter(63), new FullCharUnionFilter(AddAndConfigWiFiActivity.this), new EmojiFilter()});
        et_add_camera_username.setCustomSelectionActionModeCallback(new NotCopyAndPaste());
        et_add_camera_username.setFilters(new InputFilter[]{new InputFilter.LengthFilter(63), new FullCharUnionFilter(AddAndConfigWiFiActivity.this), new EmojiFilter()});


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but_complete:
                handButComPlete();//点击完成的业务逻辑处理
                break;
            case R.id.tv_hint://疑问解答
                View customView = View.inflate(AddAndConfigWiFiActivity.this, R.layout.pup_wifi_require, null);
                PopupWindow popupWindow = new PopupWindow(customView);
                ColorDrawable cd = new ColorDrawable(-000);
                popupWindow.setBackgroundDrawable(cd);
                popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setFocusable(true);
                popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
                TextView tv_know = customView.findViewById(R.id.tv_know);
                tv_know.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                break;
        }
    }


    private void handButComPlete() {
        str_uid = et_add_camera_uid.getText().toString().trim().toUpperCase();
        str_username = et_add_camera_username.getText().toString();
        str_password = et_add_camera_password.getText().toString();
        str_nick = getString(R.string.title_camera_fragment);
        if (str_username.length() == 0) {
            showAlert(getText(R.string.tips_null_username));
            return;
        }
        if (HiDataValue.CameraList != null && HiDataValue.CameraList.size() >= 64) {
            HiToast.showToast(this, getString(R.string.tips_limit_add_camera));
            return;
        }
        if (TextUtils.isEmpty(str_uid)) {
            showAlert(getText(R.string.tips_null_uid));
            return;
        }
        String string = HiTools.handUid(str_uid);
        str_uid = string;
        if (str_uid == null) {
            HiToast.showToast(this, getString(R.string.tips_invalid_uid));
            return;
        }
        if (str_username.getBytes().length > 63) {
            HiToast.showToast(this, getString(R.string.tips_username_tolong));
            return;
        }
        if (str_password.getBytes().length > 63) {
            HiToast.showToast(this, getString(R.string.tips_password_tolong));
            return;
        }
        if (isAP) {
            showLoadDialog(getString(R.string.adding_please_later), false, false);
            goToAdd(str_nick, str_uid, str_username, str_password);
        } else {
            handComplete();
        }
    }

    private void handComplete() {
        if (!wifiManager.isWifiEnabled()) {
            HiToast.showToast(this, getString(R.string.please_open_wifi));
            return;
        }
        mLoadHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mLoadDialoging != null && mLoadDialoging.isShowing() && !AddAndConfigWiFiActivity.this.isFinishing()) {
                    dissmissLoadDialog();
                    DoneGoToMain();
                }
            }
        }, 20000);
        showLoadDialog(getString(R.string.adding_please_later), false, false);
        goToAdd(str_nick, str_uid, str_username, str_password);
    }

    private Handler mLoadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };


    private CountDownTimer timer;

    private void chickDone() {
        goToAdd(str_nick, str_uid, str_username, str_password);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new CountDownTimer(40000, 1000) {//40秒才够配置失败,设备退回AP热点模式
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                wifiManager.startScan();
                List<ScanResult> scanResults = wifiManager.getScanResults();
                for (ScanResult scanResult : scanResults) {
                    String ssid = scanResult.SSID;
                    if (!TextUtils.isEmpty(ssid)) {
                        if (ssid.equals(mSsid) || mSsid.contains(ssid)) {
                            HiToast.showToast(AddAndConfigWiFiActivity.this, getString(R.string.config_fail_please_check_wifi));
                            dissmissLoadDialog();
                            return;
                        }
                    }
                }
                DoneGoToMain();
            }
        };
        timer.start();

    }

    private void DoneGoToMain() {
        HiToast.showToast(AddAndConfigWiFiActivity.this, getString(R.string.add_success));
        camera.saveInDatabase(AddAndConfigWiFiActivity.this);
        camera.saveInCameraList();
        Intent intentBroadcast = new Intent();
        intentBroadcast.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
        sendBroadcast(intentBroadcast);
        Intent intent = new Intent(AddAndConfigWiFiActivity.this, TakeNameToCamActivity.class);
        intent.putExtra(HiDataValue.EXTRAS_KEY_UID, camera.getUid());
        startActivity(intent);

    }

    private void goToAdd(String str_nick, String str_uid, String str_username, String str_password) {
        camera = new MyCamera(getApplicationContext(), str_nick, str_uid, str_username, str_password);
        camera.registerIOSessionListener(this);
        camera.connect();
    }


    @Override
    public void receiveSessionState(HiCamera hiCamera, int i) {
        if (hiCamera != camera) return;
        Message msg = Message.obtain();
        msg.what = HiDataValue.HANDLE_MESSAGE_SESSION_STATE;
        msg.arg1 = i;
        mHandler.sendMessage(msg);
    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != camera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = mHandler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (camera != null) {
            camera.unregisterIOSessionListener(this);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        finish();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SESSION_STATE:
                    handSessionState(msg);
                    break;
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {//成功
                        handIOCTRLSuccess(msg);
                    } else {
                        handIOCTRLFail(msg);
                    }
                    break;
            }
        }
    };

    private void handIOCTRLFail(Message msg) {
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_SET_WIFI_PARAM:
                dissmissLoadDialog();
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_LIST:
                DoneGoToMain();
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_LIST_EXT256:
                DoneGoToMain();
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_PARAM:
                dissmissLoadDialog();
                DoneGoToMain();
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_PARAM_NEWPWD255_EXT1:
                dissmissLoadDialog();
                DoneGoToMain();
                break;
        }
    }


    private void handIOCTRLSuccess(Message msg) {
        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_SET_WIFI_PARAM:
                dissmissLoadDialog();
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_LIST:
                dissmissLoadDialog();
                if (data.length >= 40) {//支持   40表示有一个
                    Intent intent = new Intent(AddAndConfigWiFiActivity.this, ConfigWiFiToDeviceTwoActivity.class);
                    intent.putExtra(HiDataValue.EXTRAS_KEY_UID, camera.getUid());
                    intent.putExtra("nick", camera.getNikeName());
                    intent.putExtra("username", camera.getUsername());
                    intent.putExtra("password", camera.getPassword());
                    intent.putExtra("mCurrentPhoneWiFi", mCurrentPhoneWiFi);
                    intent.putExtra("isSupportFullChar",isSupportFullChar);
                    startActivity(intent);
                } else {//不支持
                    DoneGoToMain();
                }
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_LIST_EXT256:
                dissmissLoadDialog();
                if (data.length >= 72) {//支持  72表示有一个
                    Intent intent = new Intent(AddAndConfigWiFiActivity.this, ConfigWiFiToDeviceTwoActivity.class);
                    intent.putExtra(HiDataValue.EXTRAS_KEY_UID, camera.getUid());
                    intent.putExtra("mCurrentPhoneWiFi", mCurrentPhoneWiFi);
                    intent.putExtra("isSupportFullChar",isSupportFullChar);
                    startActivity(intent);
                } else {//不支持
                    DoneGoToMain();
                }
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_PARAM_NEWPWD255_EXT1:
                HiChipDefines.HI_P2P_S_WIFI_PARAM_NEWPWD255_EXT1 ext1 = new HiChipDefines.HI_P2P_S_WIFI_PARAM_NEWPWD255_EXT1(data);
                String ssid = new String(ext1.strSSID);
                if (TextUtils.isEmpty(ssid)) {
                    if (camera.getCommandFunction(HiChipDefines.HI_P2P_GET_WIFI_LIST_EXT256)) {
                        camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_WIFI_LIST_EXT256, new byte[0]);//
                    } else {
                        camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_WIFI_LIST, new byte[0]);
                    }
                } else {
                    DoneGoToMain();
                }
                break;
            case HiChipDefines.HI_P2P_GET_WIFI_PARAM:
                HiChipDefines.HI_P2P_S_WIFI_PARAM wifi_param = new HiChipDefines.HI_P2P_S_WIFI_PARAM(data);
                ssid = new String(wifi_param.strSSID).trim();
                if (TextUtils.isEmpty(ssid)) {
                    if (camera.getCommandFunction(HiChipDefines.HI_P2P_GET_WIFI_LIST_EXT256)) {
                        camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_WIFI_LIST_EXT256, new byte[0]);
                    } else {
                        camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_WIFI_LIST, new byte[0]);
                    }
                } else {
                    DoneGoToMain();
                }

                break;
        }
    }

    private void handSessionState(Message msg) {
        switch (msg.arg1) {
            case HiCamera.CAMERA_CONNECTION_STATE_LOGIN:
                isSupportFullChar=camera.getCommandFunction(HiChipDefines.HI_P2P_GET_CHAR);
                if (isAP) {
                    dissmissLoadDialog();
                    Intent intent = new Intent(AddAndConfigWiFiActivity.this, ConfigWiFiToDeviceTwoActivity.class);
                    intent.putExtra(HiDataValue.EXTRAS_KEY_UID, str_uid);
                    intent.putExtra("nick", str_nick);
                    intent.putExtra("username", str_username);
                    intent.putExtra("password", str_password);
                    intent.putExtra("mCurrentPhoneWiFi", mCurrentPhoneWiFi);
                    intent.putExtra("isAP", isAP);
                    intent.putExtra("isSupportFullChar",isSupportFullChar);
                    startActivity(intent);
                    return;
                }
                if (camera.getCommandFunction(HiChipDefines.HI_P2P_GET_WIFI_PARAM_NEWPWD255_EXT1)) {
                    camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_WIFI_PARAM_NEWPWD255_EXT1, new byte[0]);
                } else {
                    camera.sendIOCtrl(HiChipDefines.HI_P2P_GET_WIFI_PARAM, null);
                }
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_DISCONNECTED:
                break;
            case HiCamera.CAMERA_CONNECTION_STATE_WRONG_PASSWORD:
                if (mLoadHandler != null) {
                    mLoadHandler.removeCallbacksAndMessages(null);
                }
                HiToast.showToast(AddAndConfigWiFiActivity.this, getString(R.string.device_info_error));
                dissmissLoadDialog();
                break;
        }
    }


}
